package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关全局过滤器：实现Token统一认证
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 统一验证Token的合法性
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求实例
        ServerHttpRequest request = exchange.getRequest();

        //2.获取响应实例
        ServerHttpResponse response = exchange.getResponse();

        //3.获取请求路径
        String path = request.getURI().getPath();

        //4.如果登录，则放行请求到目标微服务
        if(path.equals("/user/api/v1/login/login_auth/")){
            return chain.filter(exchange);
        }

        //5.获取请求头中的Token
        String token = request.getHeaders().getFirst("token");

        //6.如果Token为空，则响应401
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //7.如果Token不合法，则响应401
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claimsBody);
        if(result==0){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //8.获取Token载荷的userId并设置到请求头
        String userId = String.valueOf(claimsBody.get("id"));
        request.mutate().header("userId",userId);

        //9.放行请求到目标微服务
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0; //过滤器的执行优先级，值越小，执行优先级越高
    }
}
